// WebSocket连接管理
class WebSocketManager {
    constructor() {
        this.ws = null;
        this.connected = false;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.reconnectDelay = 4000;
        this.serverUrl = this.getWebSocketUrl();
        this.messageQueue = [];
        this.clientType = 'desktop'; // 'mobile', 'display', 'desktop'
        this.deviceInfo = null;
        this.eventListeners = new Map();

        this.detectClientType();
        this.bindEvents();
    }

    bindEvents() {
        // 绑定连接按钮事件（如果存在）
        const connectBtn = document.getElementById('connect-btn');
        const disconnectBtn = document.getElementById('disconnect-btn');
        
        if (connectBtn) {
            connectBtn.addEventListener('click', () => {
                this.connect();
            });
        }

        if (disconnectBtn) {
            disconnectBtn.addEventListener('click', () => {
                this.disconnect();
            });
        }
    }

    connect() {
        if (this.connected) {
            console.log('已经连接到服务器');
            return;
        }

        try {
            this.updateStatus('连接中...', false);

            this.ws = new WebSocket(this.serverUrl);

            this.ws.onopen = (event) => {
                console.log('WebSocket连接已建立');
                this.connected = true;
                this.reconnectAttempts = 0;
                this.updateStatus('已连接', true);
                this.updateButtons(true);

                // 保存成功连接的服务器IP
                const url = new URL(this.serverUrl);
                if (/^\d+\.\d+\.\d+\.\d+$/.test(url.hostname)) {
                    localStorage.setItem('websocket_server_ip', url.hostname);
                }

                // 发送队列中的消息
                this.flushMessageQueue();

                // 发送初始化消息
                this.sendMessage({
                    type: 'client_init',
                    clientType: this.clientType,
                    deviceInfo: this.deviceInfo,
                    userAgent: navigator.userAgent,
                    timestamp: Date.now()
                });
                
                // 触发连接成功事件
                this.dispatchEvent('websocket-connected', { clientType: this.clientType });
            };

            this.ws.onmessage = (event) => {
                try {
                    const data = JSON.parse(event.data);
                    this.handleMessage(data);
                } catch (error) {
                    console.error('解析消息失败:', error);
                }
            };

            this.ws.onclose = (event) => {
                console.log('WebSocket连接已关闭:', event.code, event.reason);
                this.connected = false;
                this.updateStatus('连接断开', false);
                this.updateButtons(false);
                
                // 触发断开连接事件
                this.dispatchEvent('websocket-disconnected', { code: event.code, reason: event.reason });

                // 自动重连
                if (event.code !== 1000 && this.reconnectAttempts < this.maxReconnectAttempts) {
                    this.scheduleReconnect();
                }
            };

            this.ws.onerror = (error) => {
                console.error('WebSocket错误:', error);
                this.updateStatus('连接错误', false);
                
                // 触发错误事件
                this.dispatchEvent('websocket-error', { error: error });
            };

        } catch (error) {
            console.error('连接失败:', error);
            this.updateStatus('连接失败', false);
        }
    }

    disconnect() {
        if (this.ws) {
            this.ws.close(1000, '用户主动断开');
            this.ws = null;
        }
        this.connected = false;
        this.reconnectAttempts = this.maxReconnectAttempts; // 阻止自动重连
        this.updateStatus('未连接', false);
        this.updateButtons(false);
    }

    scheduleReconnect() {
        this.reconnectAttempts++;
        const delay = this.reconnectDelay * this.reconnectAttempts;

        this.updateStatus(`重连中... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`, false);

        setTimeout(() => {
            if (this.reconnectAttempts <= this.maxReconnectAttempts) {
                console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
                // 如果当前服务器连接失败，尝试使用备用IP
                if (this.reconnectAttempts > 2) {
                    this.tryAlternativeServers();
                } else {
                    this.connect();
                }
            } else {
                this.updateStatus('连接失败，已达到最大重试次数', false);
            }
        }, delay);
    }

    sendMessage(data) {
        if (this.connected && this.ws && this.ws.readyState === WebSocket.OPEN) {
            try {
                this.ws.send(JSON.stringify(data));
                return true;
            } catch (error) {
                console.error('发送消息失败:', error);
                return false;
            }
        } else {
            // 将消息加入队列，等待连接建立后发送
            this.messageQueue.push(data);
            console.log('消息已加入队列，等待连接建立');
            return false;
        }
    }

    flushMessageQueue() {
        while (this.messageQueue.length > 0) {
            const message = this.messageQueue.shift();
            this.sendMessage(message);
        }
    }

    handleMessage(data) {
        console.log('收到消息:', data);
        
        // 触发通用消息事件
        this.dispatchEvent('websocket-message', data);

        switch (data.type) {
            case 'welcome':
                console.log('服务器欢迎消息:', data.message);
                break;

            case 'draw_start':
            case 'draw_move':
            case 'draw_end':
            case 'clear_canvas':
                // 转发给沙盘画布处理
                if (window.sandboxCanvas) {
                    window.sandboxCanvas.handleRemoteDrawing(data);
                }
                break;

            case 'add_object':
                // 处理添加对象消息
                if (window.sandboxCanvas && data.object) {
                    window.sandboxCanvas.drawObject(data.object);
                }
                break;

            case 'user_count':
                // 更新在线用户数
                this.updateUserCount(data.count);
                break;
                
            case 'client_list':
                // 更新客户端列表
                this.updateClientList(data.clients);
                break;

            case 'error':
                console.error('服务器错误:', data.message);
                this.showNotification('服务器错误: ' + data.message, 'error');
                break;

            case 'ping':
                // 响应心跳
                this.sendMessage({ type: 'pong', timestamp: Date.now() });
                break;

            default:
                console.log('未知消息类型:', data.type);
        }
    }

    updateStatus(text, connected) {
        const statusText = document.getElementById('status-text');
        const statusIndicator = document.getElementById('status-indicator');

        if (statusText) {
            statusText.textContent = text;
        }

        if (statusIndicator) {
            if (connected) {
                statusIndicator.classList.add('connected');
            } else {
                statusIndicator.classList.remove('connected');
            }
        }
    }

    updateButtons(connected) {
        const connectBtn = document.getElementById('connect-btn');
        const disconnectBtn = document.getElementById('disconnect-btn');

        if (connectBtn) {
            connectBtn.disabled = connected;
            connectBtn.textContent = connected ? '已连接' : '连接服务器';
        }

        if (disconnectBtn) {
            disconnectBtn.disabled = !connected;
        }
    }

    updateUserCount(count) {
        // 可以在界面上显示在线用户数
        console.log('在线用户数:', count);
    }

    showNotification(message, type = 'info') {
        // 简单的通知显示
        const notification = document.createElement('div');
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            background: ${type === 'error' ? '#e74c3c' : '#3498db'};
            color: white;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            z-index: 1000;
            font-size: 14px;
            max-width: 300px;
        `;
        notification.textContent = message;

        document.body.appendChild(notification);

        // 3秒后自动移除
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 4000);
    }

    isConnected() {
        return this.connected && this.ws && this.ws.readyState === WebSocket.OPEN;
    }

    // 设置服务器URL
    setServerUrl(url) {
        this.serverUrl = url;
    }

    // 获取WebSocket连接地址
    getWebSocketUrl() {
        // 获取当前页面的主机名
        const hostname = window.location.hostname;
        const port = '9090';
        
        // 如果是localhost，尝试使用局域网IP
        if (hostname === 'localhost' || hostname === '127.0.0.1') {
            // 从服务器启动信息中获取局域网IP，或使用默认的局域网地址
            const lanIP = this.detectLanIP();
            if (lanIP) {
                return `ws://${lanIP}:${port}`;
            }
        }
        
        return `ws://${hostname}:${port}`;
    }
    
    // 检测局域网IP
    detectLanIP() {
        // 尝试从当前URL获取IP地址
        const currentHost = window.location.hostname;
        
        // 如果当前访问的就是IP地址，直接使用
        if (/^\d+\.\d+\.\d+\.\d+$/.test(currentHost)) {
            return currentHost;
        }
        
        // 尝试从localStorage获取之前保存的IP
        const savedIP = localStorage.getItem('websocket_server_ip');
        if (savedIP && /^\d+\.\d+\.\d+\.\d+$/.test(savedIP)) {
            return savedIP;
        }
        
        // 从服务器日志中看到的默认IP
        return '192.168.1.3';
    }

    // 尝试备用服务器
    tryAlternativeServers() {
        const alternativeIPs = [
            '192.168.1.3',
            '192.168.0.100',
            '192.168.1.100',
            '127.0.0.1'
        ];
        
        const currentUrl = new URL(this.serverUrl);
        const currentIP = currentUrl.hostname;
        
        // 找到下一个可尝试的IP
        let nextIP = alternativeIPs.find(ip => ip !== currentIP);
        if (nextIP) {
            console.log(`尝试备用服务器: ${nextIP}`);
            this.serverUrl = `ws://${nextIP}:${currentUrl.port}`;
            this.connect();
        } else {
            this.connect(); // 如果没有备用IP，继续使用当前IP重试
        }
    }

    // 获取连接状态
    getConnectionState() {
        if (!this.ws) return 'CLOSED';

        switch (this.ws.readyState) {
            case WebSocket.CONNECTING:
                return 'CONNECTING';
            case WebSocket.OPEN:
                return 'OPEN';
            case WebSocket.CLOSING:
                return 'CLOSING';
            case WebSocket.CLOSED:
                return 'CLOSED';
            default:
                return 'UNKNOWN';
        }
    }

    // 检测客户端类型
    detectClientType() {
        const userAgent = navigator.userAgent.toLowerCase();
        const isMobile = /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent);
        const isTablet = /ipad|android(?!.*mobile)/i.test(userAgent);
        const screenWidth = window.screen.width;
        const screenHeight = window.screen.height;
        const maxDimension = Math.max(screenWidth, screenHeight);
        
        // 根据URL参数或页面类型确定客户端类型
        const urlParams = new URLSearchParams(window.location.search);
        const pageType = urlParams.get('type') || this.getPageType();
        
        if (pageType === 'mobile' || window.location.pathname.includes('mobile-control')) {
            this.clientType = 'mobile';
        } else if (pageType === 'display' || window.location.pathname.includes('display-screen')) {
            this.clientType = 'display';
        } else if (maxDimension >= 1920) {
            this.clientType = 'display';
        } else if (isMobile) {
            this.clientType = 'mobile';
        } else {
            this.clientType = 'desktop';
        }
        
        this.deviceInfo = {
            userAgent: navigator.userAgent,
            screenWidth: screenWidth,
            screenHeight: screenHeight,
            pixelRatio: window.devicePixelRatio || 1,
            touchSupport: 'ontouchstart' in window,
            orientation: screen.orientation ? screen.orientation.angle : 0,
            language: navigator.language,
            platform: navigator.platform
        };
        
        console.log('检测到客户端类型:', this.clientType, this.deviceInfo);
    }
    
    // 获取页面类型
    getPageType() {
        const path = window.location.pathname;
        if (path.includes('mobile-control')) return 'mobile';
        if (path.includes('display-screen')) return 'display';
        return 'desktop';
    }
    
    // 事件管理
    addEventListener(eventType, callback) {
        if (!this.eventListeners.has(eventType)) {
            this.eventListeners.set(eventType, []);
        }
        this.eventListeners.get(eventType).push(callback);
    }
    
    removeEventListener(eventType, callback) {
        if (this.eventListeners.has(eventType)) {
            const listeners = this.eventListeners.get(eventType);
            const index = listeners.indexOf(callback);
            if (index > -1) {
                listeners.splice(index, 1);
            }
        }
    }
    
    dispatchEvent(eventType, data) {
        // 触发自定义事件监听器
        if (this.eventListeners.has(eventType)) {
            this.eventListeners.get(eventType).forEach(callback => {
                try {
                    callback(data);
                } catch (error) {
                    console.error('事件监听器执行错误:', error);
                }
            });
        }
        
        // 触发DOM事件
        const event = new CustomEvent(eventType, { detail: data });
        window.dispatchEvent(event);
    }
    
    // 更新客户端列表
    updateClientList(clients) {
        console.log('客户端列表更新:', clients);
        
        // 统计不同类型的客户端
        const stats = {
            mobile: 0,
            display: 0,
            desktop: 0,
            total: clients.length
        };
        
        clients.forEach(client => {
            if (stats.hasOwnProperty(client.type)) {
                stats[client.type]++;
            }
        });
        
        // 更新界面显示
        this.updateClientStats(stats);
        
        // 触发客户端列表更新事件
        this.dispatchEvent('client-list-updated', { clients, stats });
    }
    
    // 更新客户端统计
    updateClientStats(stats) {
        const elements = {
            'mobile-count': stats.mobile,
            'display-count': stats.display,
            'desktop-count': stats.desktop,
            'total-count': stats.total
        };
        
        Object.entries(elements).forEach(([id, value]) => {
            const element = document.getElementById(id);
            if (element) {
                element.textContent = value;
            }
        });
    }
    
    // 发送消息（增强版）
    send(data) {
        // 添加客户端信息
        const message = {
            ...data,
            clientType: this.clientType,
            timestamp: data.timestamp || Date.now()
        };
        
        return this.sendMessage(message);
    }
    
    // 获取客户端类型
    getClientType() {
        return this.clientType;
    }
    
    // 设置客户端类型
    setClientType(type) {
        if (['mobile', 'display', 'desktop'].includes(type)) {
            this.clientType = type;
            console.log('客户端类型已设置为:', type);
        }
    }
    
    // 获取设备信息
    getDeviceInfo() {
        return this.deviceInfo;
    }

    // 发送心跳包
    startHeartbeat() {
        this.heartbeatInterval = setInterval(() => {
            if (this.isConnected()) {
                this.sendMessage({ type: 'ping', timestamp: Date.now() });
            }
        }, 30000); // 每30秒发送一次心跳
    }

    stopHeartbeat() {
        if (this.heartbeatInterval) {
            clearInterval(this.heartbeatInterval);
            this.heartbeatInterval = null;
        }
    }
}

// 导出类供其他文件使用
window.WebSocketManager = WebSocketManager;

// 创建全局实例
if (typeof window !== 'undefined') {
    window.websocketManager = new WebSocketManager();
}